package com.hugoo.core.slt;

import com.hugoo.core.Conf;
import com.hugoo.core.UnAuthz;
import com.hugoo.core.db.HSF;
import com.hugoo.core.db.mo.Record;
import com.hugoo.core.db.mo.RecordSet;
import com.hugoo.core.util.CryptUtil;
import com.hugoo.core.util.TL;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Lovelock.Chan
 */
public class RptSlt extends HttpServlet {

    private Log log = LogFactory.getLog(RptSlt.class);

    @Override
    public String getInitParameter(String name) {
        return super.getInitParameter(name);
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String sp = request.getServletPath();
        sp = sp.substring(sp.lastIndexOf("/") + 1);//.replace(".rpt", "");
        //---------------------------------------------------------------------
        String m = request.getParameter("m");
        String __usid__ = request.getParameter("__usid__");
        String __jolm__ = request.getParameter("__jolm__");
        HttpSession hsess = request.getSession();
        try {
            if (UnAuthz.authz(sp)) {//如果不需要过滤认证的URI，走本通道
                log.info("无须认证简易通道->" + sp);
            } else if ("216C3F6028EA542D38D5433C636852B8".equals(__usid__) && request.getRequestURI().endsWith(".file")) {
                //内部文件专用通道
                log.info("请求内部文件传输[" + request.getRequestURI() + "]……");
            } else {
                //取得系统登录用户
                RecordSet rs = (RecordSet) hsess.getAttribute("sysuser");
                if (__usid__ == null) {
                    if (rs == null) {
                        printAlertInfo(response, "[WARN001]非法用户使用");
                        return;
                    }
                } else {
                    //如果传入的__usid__不为空
                    //1、需要验证是否登录 过
                    if (rs == null || !__usid__.equals(hsess.getAttribute("__usid__"))) {//从未登录过
                        boolean xl = true;
                        if (!request.getRequestURI().endsWith(".prt")) {//目前只有打印报表会存在，特殊情况
                            try {
                                long l = Long.parseLong(__jolm__, 36);
                                if (System.currentTimeMillis() - l > 10000) {
                                    xl = false;
                                }
                            } catch (Exception e) {
                                log.info("无效的校验码值：" + __jolm__);
                                xl = false;
                            }
                        }
                        if (xl) {//传递码通过验证
                            String usrId = CryptUtil.getInstance().decryptAES(__usid__, "AuRpt");
                            String sql = Conf.getBaseProp("usr.sql");
                            String dbl = Conf.getBaseProp("usr.sql.dbl");//
                            sql = sql.replaceAll(":__usid__", usrId);
                            RecordSet<Record> rxc = HSF.query(dbl, sql);
                            if (rxc.next()) {
                                hsess.setAttribute("sysuser", rxc);
                                hsess.setAttribute("__usid__", __usid__);
                                log.info("登录信息：" + rxc);
                            } else {
                                printAlertInfo(response, "[WARN002]登录用户无效");
                                return;
                            }
                        } else {//传递码未通过验证
                            printAlertInfo(response, "[WARN003]无效的URL登录地址");
                            return;
                        }
                    }
                }
            }
            //
            if (TL.isEmpty(m)) {
                log.debug("未传入操作方法，本系统将自动转到初始方法【exec】上。");
                m = "exec";
            }

            String prx = sp.substring(sp.lastIndexOf(".") + 1);
            request.setAttribute("_sid_", sp.substring(0, sp.lastIndexOf(".")));
            //1、加载类文件并创建实例
            Class c = Class.forName(this.getInitParameter(prx));
            Object obj = c.newInstance();//创建实例
            //2、唤醒调用方法
            Method mx = c.getDeclaredMethod(m, HttpServletRequest.class, HttpServletResponse.class);
            AcFwd af = (AcFwd) mx.invoke(obj, request, response);
            if (af != null) {
                if (af.curi) {
                    response.sendRedirect(af.path);
                } else {
                    RequestDispatcher dispatcher = request.getRequestDispatcher(af.path);
                    dispatcher.forward(request, response);
                }
            }
        } catch (NoSuchMethodException ex) {
            log.info("未找到指定的方法【" + m + "】" + request.getRequestURL().toString() + "?" + request.getQueryString(), ex);
            printAlertInfo(response, "未找到指定的方法【" + m + "】");
        } catch (ClassNotFoundException ex) {
            log.info("未找到配置接口类！", ex);
            printAlertInfo(response, "未找到配置接口类");
        } catch (Exception e) {
            log.error("系统 错误！", e);
            printAlertInfo(response, e.getMessage());
        }
    }

    private void printAlertInfo(HttpServletResponse response, String info) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().append("<script>alert('").append(info).append("，请联系管理员！');</script>").close();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
